package mylist
{
	import flash.display.Bitmap;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.net.InterfaceAddress;
	import flash.net.NetworkInfo;
	import flash.net.NetworkInterface;
	import flash.system.Security;
	import flash.text.TextField;
	import flash.utils.ByteArray;
	import flash.utils.clearTimeout;
	import flash.utils.setTimeout;
	
	/**
	 * ...
	 * @author db0@qq.com
	 */
	public class MySocket extends Sprite
	{
		private static var myIp:String;
		public static var ip:String = "192.168.1.101";
		public static var port:uint = 1843;
		private var socket:CustomSocket;
		private var canDispatchs:Boolean;
		private var timeOutId:uint;
		private var msg:ByteArray;
		
		public function MySocket(msg:ByteArray, canDispatch:Boolean, index:int)
		{
			this.msg = msg;
			socket = new CustomSocket(ip, port,index);
			name = "s" + index;
			send(msg, canDispatch);
			//timeOutId = setTimeout(reSend, 30000);
		}
		
		private function reSend():void
		{
			clearTimeout(timeOutId);
			socket.removeEventListener(Event.COMPLETE, ends);
			socket.removeEventListener(CustomSocket.ERROR, ends);
			if (canDispatchs) {
			dispatchEvent(new Event(CustomSocket.ERROR));
			logs.adds("dispatchEvent time out:",CustomSocket.ERROR);
			}
			socket.kill();
			socket = null;
			msg = null;
			
			//socket = new CustomSocket(ip, port);
			//send(msg, canDispatchs);
			//timeOutId = setTimeout(reSend, 30000);
		}
		
		private function send(msg:ByteArray, canDispatch:Boolean):void
		{
			//socket.kill();
			canDispatchs = canDispatch;
			if (canDispatch)
			{
				socket.addEventListener(Event.COMPLETE, ends);
				socket.addEventListener(CustomSocket.ERROR, ends);
			}
			else
			{
				socket.removeEventListener(Event.COMPLETE, ends);
				socket.removeEventListener(CustomSocket.ERROR, ends);
			}
			if (msg)
			{
				msg.position = 0;
				//logs.adds("len:", msg.length, msg.position);
				socket.send(msg);
			}
		}
		
		public function close():void
		{
			clearTimeout(timeOutId);
			socket.removeEventListener(Event.COMPLETE, ends);
			socket.removeEventListener(CustomSocket.ERROR, ends);
			socket.kill();
			socket = null;
		}
		
		private function ends(e:Event):void
		{
			clearTimeout(timeOutId);
			socket.removeEventListener(Event.COMPLETE, ends);
			socket.removeEventListener(CustomSocket.ERROR, ends);
			
			if (canDispatchs)
			{
				dispatchEvent(e);
				logs.adds("dispatchEvent:", e.type);
			}
					msg = null;
					socket.kill();
					socket = null;
		}
		
		public static function sendBmp(time:uint, index:int, bmp:Bitmap, onComplete:Function, onError:Function):void
		{
			var bytes:ByteArray = new ByteArray();
			bytes.writeUnsignedInt(4);
			bytes.writeUnsignedInt(1);
			var bmpd:ByteArray;
			if (FileItem.list[index].jpeg) {
				logs.adds("has jpeg");
				bmpd = FileItem.list[index].jpeg;
			}else {
				var jpeg:JPGEncoder = new JPGEncoder(10);
				bmpd = jpeg.encode(bmp.bitmapData);
				FileItem.list[index].jpeg = bmpd;
			}
			bytes.writeUnsignedInt(bmpd.length);
			bytes.writeUnsignedInt(time);
			if (myIp == null)
			{
				myIp = getMyIp("127.0.0.1");
				
			}
			bytes.writeUnsignedInt(ipToUint(myIp));
			bytes.writeUnsignedInt(4);
			bytes.writeUnsignedInt(6);
			bytes.writeBytes(bmpd);
			FileItem.list[index].size = bmpd.length;
			//logs.adds("sendBmp()",index,time,bmpd.length);
			var sendBmpSock:MySocket = new MySocket(bytes, true, index);
			sendBmpSock.addEventListener(Event.COMPLETE, onComplete);
			sendBmpSock.addEventListener(CustomSocket.ERROR, onError);
		}
		
		public static function sendShow(size:uint, time:uint, index:int, onComplete:Function):void
		{
			//logs.adds("sendShow()",size,time);
			var bytes:ByteArray = new ByteArray();
			bytes.writeUnsignedInt(4);
			bytes.writeUnsignedInt(3);
			bytes.writeUnsignedInt(size);
			bytes.writeUnsignedInt(time);
			bytes.writeUnsignedInt(ipToUint(getMyIp("127.0.0.1")));
			var sendBmpSock:MySocket = new MySocket(bytes, true, index);
			sendBmpSock.addEventListener(Event.COMPLETE, onComplete);
		}
		
		private static function ipToUint(ip:String):uint
		{
			var arr:Array = ip.split(".");
			if (arr && arr.length == 4)
			{
				var i:uint = uint(arr[0]) << 24;
				i += uint(arr[1]) << 16;
				i += uint(arr[2]) << 8;
				i += uint(arr[3]);
				return i;
			}
			return 0;
		}
		
		/**
		 * 查找ip是不是本机的ip,如是,返回原ip,否则返回本机的其他ip
		 * @param    ip 需要查找的ip地址
		 * @return 一个属于本机的ip地址
		 */
		public static function getMyIp(ip:String):String
		{
			
			var networkInfo:NetworkInfo = NetworkInfo.networkInfo;
			var interfaces:Vector.<NetworkInterface> = networkInfo.findInterfaces();
			var ipArr:Array = new Array();
			if (interfaces != null)
			{
				for each (var interfaceObj:NetworkInterface in interfaces)
				{
					for each (var address:InterfaceAddress in interfaceObj.addresses)
					{
						
						if (address.ipVersion == "IPv4" && address.address != "127.0.0.1")
						{
							//logs.adds( "  type: "           + address.ipVersion );
							//logs.adds( "  address: "         + address.address );
							//logs.adds( "  broadcast: "         + address.broadcast );
							//logs.adds( "  prefix length: "     + address.prefixLength );
							ipArr.push(address.address);
							break;
						}
					}
				}
			}
			
			if (ipArr.length < 1)
				ip = "127.0.0.1";
			if (ipArr.length == 1)
				ip = ipArr[0];
			if (ipArr.length > 1)
			{
				var bool:Boolean = false;
				var otherIp:String;
				for each (var item:String in ipArr)
				{
					if (ip == item)
					{
						bool = true;
						break;
					}
					else
					{
						otherIp = item;
					}
				}
				if (!bool)
					ip = otherIp;
			}
			return ip;
		}
	}
}

import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.Socket;
import flash.utils.ByteArray;
import flash.utils.clearTimeout;
import flash.utils.setTimeout;
import mylist.*;

class CustomSocket extends Socket
{
	public static const ERROR:String = "XXXXXX";
	private var sendData:ByteArray = null;
	private var host:String;
	private var port:uint;
	
	private static const onceSize:uint = 10240;
	private var sendPostion:uint = 0;
	/**
	 * 总大小
	 */
	private var size:uint = 0;
	/**
	 * 服务器的字节数
	 */
	private var sizeSended:uint = 0;
	private var curIconIndex:int;
	
	public function CustomSocket(host:String, port:uint,index:int)
	{
		curIconIndex = index;
		this.port = port;
		this.host = host;
	}
	
	public function send(sendData:ByteArray):void
	{
		if (sendData.length > 0)
			if (size == 0)
			{
				configureListeners();
				size = sendData.length;
				this.sendData = sendData;
				//logs.adds(this.sendData.position);
				if (connected)
					close();
				if (host && port)
				{
					super.connect(host, port);
				}
			}
	}
	
	private function configureListeners():void
	{
		addEventListener(Event.CONNECT, connectedh);
		addEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler);
		
		addEventListener(IOErrorEvent.IO_ERROR, Handler);
		addEventListener(SecurityErrorEvent.SECURITY_ERROR, Handler);
		addEventListener(Event.CLOSE, Handler);
	}
	
	public function kill(sucess:Boolean = false):void
	{
		if (connected)
			close();
		this.sendData = null;
		
		removeEventListener(Event.CONNECT, connectedh);
		removeEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler);
		
		removeEventListener(IOErrorEvent.IO_ERROR, Handler);
		removeEventListener(SecurityErrorEvent.SECURITY_ERROR, Handler);
		removeEventListener(Event.CLOSE, Handler);
		
		if (sucess)
		{
			dispatchEvent(new Event(Event.COMPLETE));
				//logs.adds("dispatchEvent",Event.COMPLETE);
		}
		else
		{
			dispatchEvent(new Event(ERROR));
				//logs.adds("dispatchEvent",ERROR);
		}
		//logs.adds(size);
		size = 0;
		sizeSended = 0;
		clearTimeout(timeOutId);
	}
	
	private function connectedh(e:Event):void
	{
		if (sendData)
		{
			sendOnce();
		}
	}
	
	private var timeOutId:uint;
	private function sendOnce():void
	{
		clearTimeout(timeOutId);
		var numSize:uint = onceSize;
		if (numSize + sendPostion > size) {
			writeBytes(sendData,sendPostion);
		}else
		writeBytes(sendData,sendPostion,numSize);
		flush();
		sendPostion += onceSize;
		setTimeout(sendOnce,10);
	}
	
	private function Handler(e:Event = null):void
	{
		kill(); //---------------
	}
	
	private function socketDataHandler(e:ProgressEvent):void
	{
		sizeSended = readUnsignedInt();
		if (ViewList.main.getChildByName("c" + curIconIndex))
		IconItem(ViewList.main.getChildByName("c" + curIconIndex)).setProgress(sizeSended/size);
		logs.adds(sizeSended);
		if (sizeSended >= size)
		{
			if (sizeSended == size)
			{
				logs.adds("已发送完成,Ok!");
				kill(true);
			}
			else
			{
				logs.adds("失败！");
				kill();
			}
			
		}else {
			
		}
	}
}
